package cn.imjzm.runcarserve.controller;

import cn.imjzm.runcarserve.pojo.Result;
import cn.imjzm.runcarserve.pojo.User;
import cn.imjzm.runcarserve.service.LoginService;
import cn.imjzm.runcarserve.utils.JwtUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import java.util.HashMap;
import java.util.Map;
@CrossOrigin(origins = "*")
@RestController
@Tag(name = "登录模块", description = "用户登录相关接口")
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Operation(
            summary = "用户登录",
            description = "通过手机号和密码登录系统，登录成功后返回JWT令牌",
            requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
                    description = "用户登录信息，包含手机号和密码",
                    required = true,
                    content = @Content(
                            mediaType = "application/json",
                            schema = @Schema(implementation = User.class)
                    )
            )
    )
    @ApiResponses({
            @ApiResponse(
                    responseCode = "200",
                    description = "登录成功，返回JWT令牌",
                    content = @Content(
                            mediaType = "application/json",
                            schema = @Schema(implementation = Result.class)
                    )
            ),
            @ApiResponse(
                    responseCode = "401",
                    description = "登录失败，手机号或密码错误",
                    content = @Content(
                            mediaType = "application/json",
                            schema = @Schema(implementation = Result.class)
                    )
            ),
            @ApiResponse(
                    responseCode = "400",
                    description = "请求参数错误",
                    content = @Content(
                            mediaType = "application/json",
                            schema = @Schema(implementation = Result.class)
                    )
            ),
            @ApiResponse(
                    responseCode = "500",
                    description = "服务器内部错误",
                    content = @Content(
                            mediaType = "application/json",
                            schema = @Schema(implementation = Result.class)
                    )
            )
    })
    /**
     * 用户登录接口
     * @param user 用户信息
     * @return 登录结果
     */
    @PostMapping("/login")
    public Result userLogin(@RequestBody User user) {
        try {
            // 调用登录服务
            User userResult = loginService.userLogin(user);

            if (userResult != null) {
                // 构建JWT载荷
                Map<String, Object> userInfo = new HashMap<>();
                userInfo.put("password", userResult.getPassword());

                // 邮箱字段获取方式
                userInfo.put("email", userResult.getEmail());

                // 生成JWT令牌
                String jwt = JwtUtils.generateJwt(userInfo);

                //创建Cookie
                Cookie cookie = new Cookie("token", jwt);

                // 返回成功结果
                Map<String, Object> responseData = new HashMap<>();
                responseData.put("token", jwt);

                //用户信息Map创建
                Map<String, Object> userInfoMap = new HashMap<>();
                userInfoMap.put("username", userResult.getUsername());
                userInfoMap.put("email", userResult.getEmail());
                responseData.put("userInfo", userInfoMap);

                return Result.success(responseData);
            } else {
                return Result.error("邮箱或者密码错误");
            }
        } catch (Exception e) {
            e.printStackTrace(); // 或 log.error("登录异常", e);
            return Result.error("登录服务异常，请稍后重试");
        }
    }
    @PutMapping("/cpd")
    public Result changePwd(@RequestParam("email") String email, String oldpwd, String newpwd) {

        if (loginService.pwdEmailCheck(email, oldpwd)) {
            loginService.changePwd(newpwd, email);
        }

        return Result.success();
    };
}
